﻿/**
 * File:bc
 * Youth is just a unoptimized code!
 * -------------------------------------------------------------------------
 * Created by BigQ on 2016/9/25.
 *--------------------------------------------------------------------------
 * This technical information is confidential information,
 * without my written permission is prohibited for commercial purposes.　
 *--------------------------------------------------------------------------
 */
(function ($) {
    $.extend($.validator.messages, {
        required: "此项信息不能为空！",
        remote: "请修正该字段！",
        email: "请输入正确格式的电子邮件！",
        url: "请输入合法的网址！(http://)",
        date: "请输入合法的日期！",
        dateISO: "请输入合法的日期 (ISO)！",
        number: "请输入合法的数字！",
        digits: "只能输入整数！",
        creditcard: "请输入合法的信用卡号！",
        equalTo: "请再次输入相同的值！",
        accept: "请输入拥有合法后缀名的字符串！",
        maxlength: $.validator.format("请输入一个长度最多是 {0} 的字符串！"),
        minlength: $.validator.format("请输入一个长度最少是 {0} 的字符串！"),
        rangelength: $.validator.format("请输入一个长度介于 {0} 和 {1} 之间的字符串！"),
        range: $.validator.format("请输入一个介于 {0} 和 {1} 之间的值！"),
        max: $.validator.format("请输入一个最大为 {0} 的值！"),
        min: $.validator.format("请输入一个最小为 {0} 的值！")
    });
}(jQuery));
//
$(function () {
    $.metadata.setType("attr", "validate");
    //这个函数用了递归来实现倒计时
    var calctime = function (t, i) {
        i--;
        (i >= 0)
            ? setTimeout(function () {
            calctime(t, i);
        }, 1000)
            : $(t).remove();
    };
    if ($.validator) {
        //fix: when several input elements shares the same name, but has different id-ies....
        $.validator.prototype.elements = function () {
            var validator = this, rulesCache = {};
            // select all valid inputs inside the form (no submit or reset buttons)
            // workaround $Query([]).add until http://dev.jquery.com/ticket/2114 is solved
            return $([]).add(this.currentForm.elements)
                .filter(":input")
                .not(":submit, :reset, :image, [disabled]")
                .not(this.settings.ignore)
                .filter(function () {
                    var elementIdentification = this.id || this.name;
                    !elementIdentification && validator.settings.debug && window.console && console.error("%o has no id nor name assigned", this);
                    // select only the first element for each name, and only those with rules specified
                    if (elementIdentification in rulesCache || !validator.objectLength($(this).rules())) {
                        return false;
                    }
                    rulesCache[elementIdentification] = true;
                    return true;
                });

        };
    }
    $.validator.setDefaults({
        onfocusout: false,
        focusCleanup: false,
        focusInvalid: false,
        errorPlacement: function (error, element) {
            var relTipBaseElement = element;
            var tip = $('<label id="' + element.attr('name') + '-error" class="error" for="' + element.attr('id') + '">' + error.html() + '</label>');
            if (element.attr('valtipele')) {
                relTipBaseElement = $(element.attr('valtipele'));
                tip.insertAfter(relTipBaseElement);
            }
            else if (element.is('input')) {
                if (element.hasClass('checkbox')) {
                    tip.attr('for', element.attr('name'));
                    relTipBaseElement = element.nextAll('label').last();
                }
                else if (element.hasClass('radio')) {
                    tip.attr('for', element.attr('name'));
                    relTipBaseElement = element.nextAll('label').last();
                }
                tip.insertAfter(relTipBaseElement);
            }
            else if (element.is('select')) {
                relTipBaseElement = element.parent().parent();
                if (!relTipBaseElement.length || !relTipBaseElement.hasClass('dropdown')) {
                    relTipBaseElement = element;
                }
                relTipBaseElement.addClass('error');
                tip.insertAfter(relTipBaseElement);
            }
            else if (element.is('textarea')) {
                relTipBaseElement = element.next();
                if (!relTipBaseElement.length || !relTipBaseElement.is('br')) {
                    relTipBaseElement = element;
                }
                tip.insertAfter(relTipBaseElement);
            }
        },
        success: function (element) {
            var idPg = element.attr('id');
            if (idPg.indexOf("[") == -1) {
                var rElement = $('#' + element.attr('id'));
                if (!rElement.length) {
                    rElement = element;
                }
                if (rElement.prev().hasClass('dropdown')) {
                    rElement.prev().removeClass('error');
                }
                rElement.remove();
            }
        }

    });
});
//自定义验证规则
// 正整数
$.validator.addMethod("positiveInt", function (value, element) {
    var aint = parseInt(value);
    return aint > 0 && (aint + "") == value;
}, "请输入正整数！");
// 邮政编码验证   
$.validator.addMethod("zipcode", function (value, element) {
    var tel = /^[0-9]{6}$/;
    return this.optional(element) || (tel.test(value));
}, "请输入正确的邮政编码！");
//钱，2位小数
$.validator.addMethod("money", function (value, element) {
    var tel = /^\d+\.?\d{0,2}$/;
    return this.optional(element) || (tel.test(value));
}, "请输入正确的格式金钱！");

//仅中文
$.validator.addMethod("chinese", function (value, element) {
    var tel = /^[\u4e00-\u9fa5]+$/;
    return this.optional(element) || (tel.test(value));
}, "只能输入汉字！");
// 只能输入英文
$.validator.addMethod("english", function (value, element) {
    var chrnum = /^([a-zA-Z]+)$/;
    return this.optional(element) || (chrnum.test(value));
}, "只能输入字母");
$.validator.addMethod("chen", function (value, element) {
    var zreg = /^[\u4e00-\u9fa5a-zA-Z]+$/;
    ;
    return this.optional(element) || zreg.test(value);
}, "只能输入汉字或字母");
// 身份证号码验证       
$.validator.addMethod("idcard", function (value, element) {
    return this.optional(element) || isIdCardNo(value);
}, "请输入正确的身份证号码！");

// 手机号码验证       
$.validator.addMethod("mobile", function (value, element) {
    var length = value.length;
    var mobile = /^0?1[3|4|5|6|7|8][0-9]\d{8}$/;
    return this.optional(element) || (length == 11 && mobile.test(value));
}, "请输入正确的手机号码！");

// 电话号码验证       
$.validator.addMethod("telphone", function (value, element) {
    var tel = /^\d{3,4}-?\d{7,9}$/;    //电话号码格式010-12345678   
    return this.optional(element) || (tel.test(value));
}, "请输入正确的电话号码！(010-xxxxxxxx)");

// 联系电话(手机/电话皆可)验证   
$.validator.addMethod("phone", function (value, element) {
    var length = value.length;
    var mobile = /^(((13[0-9]{1})|(15[0-9]{1}))+\d{8})$/;
    var tel = /^\d{3,4}-?\d{7,9}$/;
    return this.optional(element) || (tel.test(value) || mobile.test(value));

}, "请输入正确的联系电话！");
// Decimal      
$.validator.addMethod("decimal", function (value, element) {
    var tel = /^\d+\.?\d{0,2}$/;    // 
    return this.optional(element) || (tel.test(value));
}, "请输入正确的数字！");
// 年份   
$.validator.addMethod("year", function (value, element) {
    return this.optional(element) || isYear(value);
}, "请输入正确的年份！");
// 月份
$.validator.addMethod("month", function (value, element) {
    return this.optional(element) || isMonth(value);
}, "请输入正确的月份！");
// 图片
$.validator.addMethod("image", function (value, element) {
    return this.optional(element) || checkImgType(value);
}, "图片格式不被支持！");
//文件
$.validator.addMethod("document", function (value, element) {
    return this.optional(element) || checkFileType(value);
}, "文件格式不被支持！");


//判断是否为合法的居民身份证
function isCardID(sId) {
    var aCity = {
        11: "北京",
        12: "天津",
        13: "河北",
        14: "山西",
        15: "内蒙古",
        21: "辽宁",
        22: "吉林",
        23: "黑龙江",
        31: "上海",
        32: "江苏",
        33: "浙江",
        34: "安徽",
        35: "福建",
        36: "江西",
        37: "山东",
        41: "河南",
        42: "湖北",
        43: "湖南",
        44: "广东",
        45: "广西",
        46: "海南",
        50: "重庆",
        51: "四川",
        52: "贵州",
        53: "云南",
        54: "西藏",
        61: "陕西",
        62: "甘肃",
        63: "青海",
        64: "宁夏",
        65: "新疆",
        71: "台湾",
        81: "香港",
        82: "澳门",
        91: "国外"
    };
    var iSum = 0;
    var info = "";
    if (!/^\d{17}(\d|x)$/i.test(sId)) return false;
    sId = sId.replace(/x$/i, "a");
    if (aCity[parseInt(sId.substr(0, 2))] == null) return false;
    sBirthday = sId.substr(6, 4) + "-" + Number(sId.substr(10, 2)) + "-" + Number(sId.substr(12, 2));
    var d = new Date(sBirthday.replace(/-/g, "/"));
    if (sBirthday != (d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate())) return false;
    for (var i = 17; i >= 0; i--) iSum += (Math.pow(2, i) % 11) * parseInt(sId.charAt(17 - i), 11);
    if (iSum % 11 != 1) return false;
    return true;
}
function isYear(year) {
    if (isNaN(year)) {
        return false;
    }
    else if (parseInt(year) < 1900 || parseInt(year) > 9000) {
        return false;
    }
    else {
        return true
    }
    ;
}
function isMonth(month) {
    if (isNaN(month)) {
        return false;
    }
    else if (parseInt(month) < 1 || parseInt(month) > 12) {
        return false;
    }
    else {
        return true;
    }
}
function checkImgType(filevalue) {
    var filename = new String(filevalue); //文件名
    var extension = new String(filename.substring(filename.lastIndexOf(".") + 1, filename.length)); ////文件扩展名
    if (extension.toLowerCase() == "jpg" || extension.toLowerCase() == "gif" || extension.toLowerCase() == "bmp" || extension.toLocaleLowerCase() == "png" || extension.toLocaleLowerCase() == "jpeg") {//判断文件扩展名
        return true;

    }
    else {
        return false;
    }
}
function checkFileType(filevalue) {
    var filename = new String(filevalue); //文件名
    var extension = new String(filename.substring(filename.lastIndexOf(".") + 1, filename.length)); ////文件扩展名
    var fileArr = ["zip", "7z", "rar", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "wps", "txt", "pdf"];
    if ($.inArray(extension.toLowerCase(), fileArr) >= 0) {//判断文件扩展名
        return true;

    }
    else {
        return false;
    }
}
function checkEmail(str) {
    var reg = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
    return reg.test(str);
}
function checkEnNum(str) {
    var reg = /^[a-zA-Z0-9]*$/;
    return reg.test(str);

}